<?php
namespace Common\Controller;  
use Think\Controller;  
use Common\Service\ValidataService;
/**
 * 基类
 * @author liuyang
 * 
 */
class BaseController extends Controller { 
     
    public function _initialize(){
        //验证每个接口必须要带的参数
        //$this->validateParam(array("app_version","device"));
       // $this->versionControl();
    }
    /**
     * 拼装参数成URL参数
     * @param unknown $paramlist
     * @return string
     */
    public function getUrlParam($paramlist){
        $paramStr = "";
        foreach($paramlist as $key=>$val){
            $paramStr .= $key."=".urlencode($val)."&";
        }
        return $paramStr;
    }
    
    public function getFieldByObj($obj,$fields){
        $rst = array();
        foreach($fields as $field){
            $rst[$field]=$obj[$field];
        }
        return $rst;
    }
    
  
	/**格式化为json格式 
	 */
	public function formatjson($data=array()){ 
		
		$data['server_time']=time();  
		$callback = $this->getGetParam("callback", null);  
		if(!isset($callback) || $callback == ""){
		  header ("Content-Type:application/json; charset=utf-8;"); 
		  echo json_encode($data); 
		}else{
		  header ( "Content-Type:text/html; charset=utf-8" );
		  echo $callback."(".json_encode($data).")";
		}
		exit();
	}
	/**格式为jsonp格式
	 */
	public function formatjsonp($data=array(),$callback="config"){ 
		header ( "Content-Type:text/html; charset=utf-8" );
		$data['server_time']=time();
		$data['share']=true; 
		echo $callback."(".json_encode($data).")";
	} 
	
	/**获取POST参数
	 */
    public function getPostParam($key,$default = null){
		//$reqVal=I("request.".$key);
        $reqVal=$_REQUEST[$key];
		if(!isset($reqVal)&&$default != null)
		    $reqVal=$default; 
		return $reqVal;
	}
	/**获取GET参数
	 */
	public function getGetParam($key,$default=null){
	    //$reqVal=I("request.".$key);
        $reqVal=$_REQUEST[$key];
	    if(!isset($reqVal)&&$default != null)
	        $reqVal=$default;
	    return $reqVal;
	}
	/**
     *验证参数
	 */
	public function validateParam($params){
	    $rst = array();
	    foreach ($params as $param){ 
	        $val=$this->getPostParam($param,""); 
	        if($val==null){
	            $rst=array();
	            $rst['msg']=$param."参数不对";
	            $rst['result']=-2;
	            $this->formatjson($rst); 
	        }else{
	            $rst[$param]=$val;
	        }
	    }
	    return $rst; 
	}
	
	public function getCommonFormatJson($rstId,$msg,$errMsg="提交失败"){
	    $rst = array();
	    if($rstId>0){
	        $rst['result']=200;
	        $rst['msg']=$msg;
	    }else{
	        $rst['result']=202;
	        $rst['msg']=$errMsg;
	    }
	    $this->formatjson($rst);
	}

    public function json()
    {
        $body = file_get_contents('php://input');
        if (!$body) {
            return null;
        }
        return json_decode($body, true);
    }
}